﻿using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;

namespace Monti.Controls
{
   /// <summary>
   /// A text block that you can bind runs to.
   /// </summary>
   public class BindRunsTextBlock : TextBlock
   {
      /// <summary>
      /// Dependency property for binding to text block's runs.
      /// </summary>
      public static readonly DependencyProperty RunsProperty =
         DependencyProperty.Register ("Runs", typeof (IEnumerable<Run>), 
         typeof (BindRunsTextBlock), new PropertyMetadata (default(IEnumerable<Run>), RunsChanged));

      /// <summary>
      /// Gets or Sets the runs in the text block.
      /// </summary>
      public IEnumerable<Run> Runs
      {
         get { return (IEnumerable<Run>) GetValue (RunsProperty); }
         set { SetValue (RunsProperty, value); }
      }

      /// <summary>
      /// Occurs when the runs change.
      /// </summary>
      /// <param name="d">DependencyObject BindRunsTextBlock.</param>
      /// <param name="e">DependencyPropertyChangedEventArgs</param>
      private static void RunsChanged (DependencyObject d, DependencyPropertyChangedEventArgs e)
      {
         var textBlock = d as BindRunsTextBlock;
         if (textBlock != null)
            textBlock.SetRuns ();
      }

      /// <summary>
      /// Sets up the runs.
      /// </summary>
      private void SetRuns ()
      {
         this.Inlines.Clear ();
         foreach (var run in this.Runs)
         {
            this.Inlines.Add (run);
         }
      }
   }
}
